﻿namespace System.IO
{
    /// <summary>
    /// 二进制写入文件的基类
    /// </summary>
    public class FileWriter: IDisposable
    {
        /// <summary>
        /// 文件基础信息
        /// </summary>
        public FileInfo FileInfo;

        /// <summary>
        /// 用以写入数据的二进制流文件
        /// </summary>
        protected BinaryWriter _BinaryWriter;

        public FileWriter(string FileFullName)
        {
                FileInfo = new FileInfo(FileFullName);
                _BinaryWriter = new BinaryWriter(File.Open(FileInfo.FullName, FileMode.Create));
        }

        public virtual void Dispose()
        {
            if (FileInfo != null)
            {
                FileInfo = null;
            }
            if (_BinaryWriter != null)
            {
                //_BinaryWriter.Dispose();

                _BinaryWriter.Close();

                _BinaryWriter = null;
            }
        }

        ~FileWriter()
        {
            Dispose();
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        public virtual long Write(object Data,int positin = -1)
        {
            if (_BinaryWriter == null)
            {
                Console.WriteLine(string.Format("{0} _BinaryReader is null.", GetType().Name));
                return 0;
            }

            _BinaryWriter.BaseStream.Position = positin > 0 ? positin : _BinaryWriter.BaseStream.Position;

            if (Data.GetType() != typeof(byte[]))
            {
                byte[] RawData = Data.ToBytes();
                _BinaryWriter.Write(RawData);
            }else
            {
                _BinaryWriter.Write((byte[])Data);
            }
            return _BinaryWriter.BaseStream.Position;
        }
    }
}
